/**
 * @param {Number} count
 * @return {Function}
 * @Author: Hisun 958306134@qq.com
 * @Date: 2024-07-30 22:06:47
 * @Description: 模拟生成异步任务组
 */
function mockTasks(count = 1) {
  function _asyncFunc(index) {
    const duration = Math.ceil(Math.random() * 1000 + 500);
    return () => {
      console.log(`任务${index}: 开始...`);
      return new Promise((resolve) => {
        const timer = setTimeout(() => {
          clearTimeout(timer);
          console.log(`任务${index}: `, "...完成, 耗时", duration, "ms");
          resolve();
        }, duration);
      });
    };
  }
  const tasks = new Array(count)
    .fill(0)
    .map((_, index) => _asyncFunc(index + 1));
  return tasks;
}
/**
 * @param {Function []} tasks
 * @param {Number} paralleCount
 * @return {*}
 * @Author: Hisun 958306134@qq.com
 * @Date: 2024-07-30 21:40:04
 * @Description: 并发执行任务
 */
function paralleTask(tasks, paralleCount = 2) {
  return new Promise((resolve) => {
    if (tasks.length === 0) {
      resolve();
      return;
    }
    // 记录下一个任务的下标
    let nextIndex = 0;
    // 记录完成任务的数量
    let finishCount = 0;
    let len = tasks.length;
    function _run() {
      // 运行下一个任务
      const task = tasks[nextIndex];
      nextIndex++;
      task().then(() => {
        finishCount++;
        if (nextIndex < len) {
          _run();
        } else if (finishCount === len) {
          // 任务完成
          resolve();
        }
      });
    }
    for (let i = 0; i < paralleCount && i < len; i++) {
      _run();
    }
  });
}

paralleTask(mockTasks(10), 4).then(() => {
  console.log("全部任务执行结束!");
});
